﻿#region License
// MIT License
//
// Copyright(c) 2019-2025 ZhangYu
// https://gitee.com/zhangyu800/litebyte
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#endregion
#region Intro
// Purpose: Convert base type to bytes
// Author: ZhangYu
// CreateDate: 2025-02-13
// LastModifiedDate: 2025-08-26
#endregion
namespace LiteByte.Converters {

    using System.Text;
    using LiteByte.Common;

    /// <summary> 基本类型读取器 | Base type writer </summary>
    public class BaseTypeReader : NumberReader {

        #region 字段 | Fields
        /// <summary> Decimal字符列表 </summary>
        protected static readonly char[] DecimalChars = new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.' };
        /// <summary> Java时间戳(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks) </summary>
        protected const long EpochTicks = 621355968000000000;
        // 字符串编码器
        protected static Encoding ASCII = Encoding.ASCII;
        protected static Encoding UTF8 = Encoding.UTF8;
        protected static Encoding UTF16 = Encoding.Unicode;
        protected static Encoding UTF32 = Encoding.UTF32;
        private static Encoding gbk = null;
        protected static Encoding GBK {
            get {
                if (gbk == null) {
                    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                    gbk = Encoding.GetEncoding("GBK");
                }
                return gbk;
            }
        }
        #endregion

        #region 构造方法 | Constructors
        public BaseTypeReader() : base() { }
        public BaseTypeReader(byte[] bytes) : base(bytes) { }
        #endregion

        #region 十进制小数 | Decimal
        /// <summary> 读取十进制小数 | Read decimal </summary>
        public decimal ReadDecimal() {
            bool isNegative = ReadBit1();
            ulong length = ReadVUInt32();
            StringBuilder sb = new StringBuilder(isNegative ? (int)length + 1 : (int)length);
            if (isNegative) sb.Append('-');
            for (int i = 0; i < (int)length; i++) {
                int v = ReadBits(4);
                if (v > DecimalChars.Length) throw new Exception($"ReadDecimal() error! Invalid decimal value:{v}");
                sb.Append(DecimalChars[v]);
            }
            return decimal.Parse(sb.ToString());
        }
        #endregion

        #region 日期时间 | DateTime
        /// <summary> 读取日期时间 | Read DateTime </summary>
        public DateTime ReadDateTime() {
            // Java毫秒时间戳 转为 C# Ticks (Java时间戳：自UTC 1970年1月1日午夜以来的毫秒数. 1 Tick = 10000毫秒）
            long timestamp = ReadVInt64();
            return new DateTime(timestamp * 10000 + EpochTicks);
        }
        #endregion

        #region 字符串 | String
        /// <summary> 读取变长Unicode字符串 | Read variable-length unicode string </summary>
        public string ReadVUnicode() {
            if (ReadBit1()) return null;
            int charCount = ReadVInt32();
            if (charCount == 0) return "";
            StringBuilder sb = new StringBuilder(charCount);
            for (int i = 0; i < charCount; i++) {
                uint codePoint = ReadVUInt32();
                if (codePoint >= 0xD800 && codePoint <= 0xDBFF) {
                    // char.IsHighSurrogate : charCode = 0xD800 ~ 0xDBFF
                    throw new Exception($"ReadVUnicode() error! Invalid unicode code point:{codePoint}. Code point can not be high surrogate (0xD800 ~ 0xDBFF)");
                } else {
                    sb.Append(codePoint < 65536 ? (char)codePoint : char.ConvertFromUtf32((int)codePoint));
                }
            }
            return sb.ToString();
        }

        /// <summary> 读取ASCII编码字符串 | Read ASCII string </summary>
        public string ReadASCII() {
            return ReadString(ASCII);
        }

        /// <summary> 读取UTF-8编码字符串 | Read UTF-8 string </summary>
        public string ReadUTF8() {
            return ReadString(UTF8);
        }

        /// <summary> 读取UTF-16编码字符串 | Read UTF-16 string </summary>
        public string ReadUTF16() {
            return ReadString(UTF16);
        }

        /// <summary> 读取UTF-32编码字符串 | Read UTF-32 string </summary>
        public string ReadUTF32() {
            return ReadString(UTF32);
        }

        /// <summary> 读取GBK编码字符串 | Read GBK string </summary>
        public string ReadGBK() {
            return ReadString(GBK);
        }

        protected string ReadString(Encoding encoding) {
            if (ReadBit1()) return null;
            uint byteCount = ReadVUInt32();
            if (byteCount == 0) return "";
            string value = encoding.GetString(bytes, byteIndex, (int)byteCount);
            byteIndex += (int)byteCount;
            return value;
        }
        #endregion

        #region 基本类型 | BaseType
        /// <summary> 读取基本类型数据 | Read base type data </summary>
        public object ReadBaseType(TypeName baseType) {
            switch (baseType) {
                case TypeName.Bit1: return ReadBit1();
                case TypeName.Bit2: return ReadBit2();
                case TypeName.Bit3: return ReadBit3();
                case TypeName.Bit4: return ReadBit4();
                case TypeName.Bit5: return ReadBit5();
                case TypeName.Bit6: return ReadBit6();
                case TypeName.Bit7: return ReadBit7();
                case TypeName.Bit8: return ReadBit8();
                case TypeName.Bool: return ReadBool();
                case TypeName.Char: return ReadChar();
                case TypeName.UInt8: return ReadUInt8();
                case TypeName.UInt16: return ReadUInt16();
                case TypeName.UInt32: return ReadUInt32();
                case TypeName.UInt64: return ReadUInt64();
                case TypeName.Int8: return ReadInt8();
                case TypeName.Int16: return ReadInt16();
                case TypeName.Int32: return ReadInt32();
                case TypeName.Int64: return ReadInt64();
                case TypeName.Float16: return ReadFloat16();
                case TypeName.Float32: return ReadFloat32();
                case TypeName.Float64: return ReadFloat64();
                case TypeName.VUInt16: return ReadVUInt16();
                case TypeName.VUInt32: return ReadVUInt32();
                case TypeName.VUInt64: return ReadVUInt64();
                case TypeName.VInt16: return ReadVInt16();
                case TypeName.VInt32: return ReadVInt32();
                case TypeName.VInt64: return ReadVInt64();
                case TypeName.Decimal: return ReadDecimal();
                case TypeName.DateTime: return ReadDateTime();
                case TypeName.VUnicode: return ReadVUnicode();
                case TypeName.ASCII: return ReadASCII();
                case TypeName.UTF8: return ReadUTF8();
                case TypeName.UTF16: return ReadUTF16();
                case TypeName.UTF32: return ReadUTF32();
                case TypeName.GBK: return ReadGBK();
                default: return null;
            }
        }
        #endregion

    }

}
